package com.haidechizi.doublecache.process;


import com.haidechizi.doublecache.annotation.DoubleCache;
import com.haidechizi.doublecache.enums.CacheType;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
public class GetProcessService extends BaseProcessService {

    @Override
    protected void doProcess(ProcessContext processContext) throws Throwable {
        //读写，查询Caffeine
        String cacheKey = processContext.getCacheKey();
        DoubleCache doubleCache = processContext.getDoubleCache();
        Object localCache = localCacheService.getCache(cacheKey);
        if (Objects.nonNull(localCache)) {
            log.info("get data from localCache");
            processContext.setValue(localCache);
            return;
        }

        //查询Redis
        Object removeCache = remoteCacheService.getCache(cacheKey);
        if (Objects.nonNull(removeCache)) {
            log.info("get data from removeCache");
            localCacheService.setCache(cacheKey, removeCache, doubleCache.firstCacheTimeout());
            processContext.setValue(removeCache);
            return;
        }

        log.info("get data from database");
        Object object = processContext.proceed();
        if (Objects.nonNull(object)) {
            localCacheService.setCache(cacheKey, object, doubleCache.firstCacheTimeout());
            remoteCacheService.setCache(cacheKey, object, doubleCache.secondCacheTimeout());
        }
        processContext.setValue(object);
    }

    @Override
    protected String name() {
        return CacheType.GET.getCode();
    }
}
